package org.example.lotterysystem.common.pojo;

import lombok.Data;
import org.example.lotterysystem.common.errorcode.ErrorCode;
import org.example.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import org.springframework.util.Assert;
import java.io.Serializable;
import java.util.Objects;

@Data
public class CommonResult<T> implements Serializable {
    /**
     * 返回的错误码
     */
    private Integer code;

    /**
     * 正常返回数据
     */
    private T data;

    /**
     * 错误码描述
     */
    private String msg;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CommonResult<?> result = (CommonResult<?>) o;
        return Objects.equals(code, result.code) && Objects.equals(data, result.data) && Objects.equals(msg, result.msg);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code, data, msg);
    }

    @Override
    public String toString() {
        return "CommonResult{" +
                "code=" + code +
                ", data=" + data +
                ", msg='" + msg + '\'' +
                '}';
    }

    public static <T> CommonResult<T> success(T data){
        CommonResult<T> result = new CommonResult<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = "";
        return result;
    }

    public static <T> CommonResult<T> error(Integer code,String msg){
        Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code)
                ,"code不是错误的异常");
        CommonResult<T> result = new CommonResult<>();
        result.code = code;
        result.msg = msg;
        return result;
    }
    public static <T> CommonResult<T> error(ErrorCode code){
        return error(code.getCode(),code.getMsg());
    }
}
